const program = require('commander');
const fs = require('fs-extra');
const { execSync } = require('child_process');
const archiver = require('archiver');
const path = require("path");
const chalk = require('chalk')
const resolve = dir => path.join(__dirname, "..", dir);
const { cdnActivitys } = require('../cdn.config');

function camelize (str) {
  return str.replace(/-(\w)/g, (_, c) => c ? c.toUpperCase() : '')
}

function cleanArgs (cmd) {
  const args = {}
  cmd.options.forEach(o => {
    const key = camelize(o.long.replace(/^--/, ''))
    if (typeof cmd[key] !== 'function' && typeof cmd[key] !== 'undefined') {
      args[key] = cmd[key]
    }
  })
  return args
}

let _hasYarn

const hasYarn = () => {
  if (_hasYarn != null) {
    return _hasYarn
  }
  try {
    execSync('yarn --version', { stdio: 'ignore' })
    return (_hasYarn = true)
  } catch (e) {
    return (_hasYarn = false)
  }
}

program.command('dev <activity>').option('-mode <projectMode>', 'project mode').action((activity, cmd) => {
  const options = cleanArgs(cmd);
  const mode = options.Mode || 'development';
  execSync(`cross-env activity=${activity} APP_ENV=${mode} vue-cli-service serve`, { stdio: [0, 1, 2] });
});

program.command('test <activity>').option('-mode <projectMode>', 'project mode').action((activity, cmd) => {
  const options = cleanArgs(cmd);
  const mode = options.Mode || 'test';
  execSync(`cross-env activity=${activity} APP_ENV=${mode} vue-cli-service build`, { stdio: [0, 1, 2] });
});

program.command('build <activity>').option('-mode <projectMode>', 'project mode').action((activity, cmd) => {
  const options = cleanArgs(cmd);
  const mode = options.Mode || 'production';
  execSync(`cross-env activity=${activity} APP_ENV=${mode} vue-cli-service build`, { stdio: [0, 1, 2] });
  if(cdnActivitys[activity]){
    //上传CDN 需accessKey scrtkey 待运维给heyheystatic单独key后再开放key的使用
    execSync(`qshell qupload2 --src-dir=D:\\work\\h5-vue3\\dist\\${activity} --bucket=heyheystatic --key-prefix="h5-activity/dist/${activity}/" --thread-count=10 --overwrite --rescan-local --check-size`, { stdio: [0, 1, 2] });
    //刷新模版html的cdn缓存
    execSync(`qshell cdnrefresh -i D:\\work\\h5-vue3\\src\\activities\\${activity}\\cdnrefreshfile.txt`, { stdio: [0, 1, 2] });
    execSync(`qshell cdnrefresh -i D:\\work\\h5-vue3\\src\\activities\\${activity}\\cdnrefreshdir.txt`, { stdio: [0, 1, 2] });
  }
});

program.command('report <activity>').option('-mode <projectMode>', 'project mode').action((activity, cmd) => {
  const options = cleanArgs(cmd);
  const mode = options.Mode || 'production';
  execSync(`cross-env activity=${activity} APP_ENV=${mode} vue-cli-service build --report`, { stdio: [0, 1, 2] });
});

const compressFile = (targetDir, localFile, name = false) => {
  return new Promise((resolve, reject) => {
    const output = fs.createWriteStream(localFile);
    const archive = archiver('zip', {
      zlib: { level: 9 }
    });

    output.on('close', () => {
      resolve(console.log('压缩完成！共计 ' + (archive.pointer() / 1024 /1024).toFixed(3) + 'MB'))
    }).on('error', (err) => {
      reject(console.error('压缩失败', err))
    })

    archive.pipe(output);
    archive.directory(targetDir, name);
    archive.finalize();
  })
}


const UPLOAD_URL = 'http://109.244.37.67:8181/upload';

program.command('release <activity>').action(async (activity, cmd) => {
  console.log('发布执行：', activity);
  // execSync(`cross-env activity=${activity} APP_ENV=production vue-cli-service build`, { stdio: [0, 1, 2] });
  // console.log('项目打包成功。');
  const options = cleanArgs(cmd);
  const mode = options.Mode || 'production';
  execSync(`cross-env activity=${activity} APP_ENV=${mode} vue-cli-service build`, { stdio: [0, 1, 2] });
  if(cdnActivitys[activity]){
    //上传CDN 需accessKey scrtkey 待运维给heyheystatic单独key后再开放key的使用
    execSync(`qshell qupload2 --src-dir=D:\\work\\h5-vue3\\dist\\${activity} --bucket=heyheystatic --key-prefix="h5-activity/dist/${activity}/" --thread-count=10 --overwrite --rescan-local --check-size`, { stdio: [0, 1, 2] });
    //刷新模版html的cdn缓存
    execSync(`qshell cdnrefresh -i D:\\work\\h5-vue3\\src\\activities\\${activity}\\cdnrefreshfile.txt`, { stdio: [0, 1, 2] });
    execSync(`qshell cdnrefresh -i D:\\work\\h5-vue3\\src\\activities\\${activity}\\cdnrefreshdir.txt`, { stdio: [0, 1, 2] });
  }

  const zipName = resolve(`dist/${activity}_${Date.now()}.zip`);
  await compressFile(resolve(`dist/${activity}`), zipName, activity);
  const update = `curl -F "type=v-13/tools/backup" -F "user=sch" -F "action=upload" -F file=@${zipName} ${UPLOAD_URL}`
  const result = execSync(update);
  if(result.toString().endsWith(0)) {
    console.log('文件上传成功：', zipName);
  } else {
    console.error('文件上传失败');
  }
  fs.removeSync(zipName);
  console.info(`巨人云工单地址：${chalk.cyan('http://cloud.ztgame.com.cn/pangu/issuance/modular/111/copy/691/16175')}`)
  console.info(`活动正式访问地址：${chalk.cyan(`https://www.heyheytalk.com/campaign/${activity}/`)}`)
})


program.command('rstatic <activity>').action(async (activity, cmd) => {
  console.log('发布执行：', activity);
 
  const zipName = resolve(`dist/${activity}_${Date.now()}.zip`);
  await compressFile(resolve(`dist/${activity}`), zipName, activity);
  const update = `curl -F "type=v-13/tools/backup" -F "user=sch" -F "action=upload" -F file=@${zipName} ${UPLOAD_URL}`
  const result = execSync(update);
  if(result.toString().endsWith(0)) {
    console.log('文件上传成功：', zipName);
  } else {
    console.error('文件上传失败');
  }
  fs.removeSync(zipName);
  console.info(`巨人云工单地址：${chalk.cyan('http://cloud.ztgame.com.cn/pangu/issuance/modular/111/copy/691/16175')}`)
  console.info(`活动正式访问地址：${chalk.cyan(`https://www.heyheytalk.com/campaign/${activity}/`)}`)
})

program.parse(process.argv);
